<!-- pages/login/components/mobile.vue -->
<script setup>
	import { getCodeApi, loginApi } from '@/apis/user'
	// 是否显示倒计时
	import { ref } from 'vue'
	// store
	import { useUserStore } from '@/stores/user'
	const showCountdown = ref(false)
	const getCode = async () => {
		try {
			// 表单校验
			// 校验表单部分字段
			await form.value.validateField(['mobile'])
			// 校验通过之后 再去修改显示
			showCountdown.value = true
			//  获取验证码
			// 必须使用 测试账号的手机号 才可以正常获取验证码，别写错了
			const res = await getCodeApi({
				mobile: formData.value.mobile,
				type: 'login',
			})
			// console.log(res)
			uni.showToast({
				title: res.code,
			})
		} catch (e) {
			//TODO handle the exception
		}
	}
	// 表单校验
	// 表单数据
	const formData = ref({
		mobile: '',
		code: '',
	})
	// 表单 ref
	const form = ref()
	// 校验规则
	const formRules = {
		mobile: {
			rules: [
				{ required: true, errorMessage: '请填写手机号码' },
				{ pattern: '^1\\d{10}$', errorMessage: '手机号码格式不正确' },
			],
		},
		code: {
			rules: [
				{ required: true, errorMessage: '请输入验证码' },
				{ pattern: '^\\d{6}$', errorMessage: '验证码格式不正确' },
			],
		},
	}

	// 登录
	const isAgree = ref(false)
	// 仓库对象
	const store = useUserStore()
	const loginFunc = async () => {
		if (!isAgree.value) {
			return uni.showToast({
				title: '请勾选协议',
				icon: 'error',
			})
		}
		try {
			await form.value.validate()
			// 调用登录接口获取登录之后的信息即可
			const res = await loginApi({
				mobile: formData.value.mobile,
				code: formData.value.code,
			})
			// console.log(res)
			store.token = res.token
			// 去我的页面即可
			// tab管理的页面用 switchTab 切换即可
			uni.switchTab({
				url: '/pages/my/index',
			})
		} catch (e) {
			//TODO handle the exception
		}
	}
	const radioChange = () => {
		isAgree.value = !isAgree.value
	}
</script>

<template>
	<uni-forms class="login-form" ref="form" :model="formData" :rules="formRules">
		<uni-forms-item name="mobile">
			<uni-easyinput
				v-model="formData.mobile"
				:input-border="false"
				:clearable="false"
				placeholder="请输入手机号"
				placeholder-style="color: #C3C3C5"
			/>
		</uni-forms-item>
		<uni-forms-item name="code">
			<uni-easyinput
				v-model="formData.code"
				:input-border="false"
				:clearable="false"
				placeholder="请输入验证码"
				placeholder-style="color: #C3C3C5"
			/>
			<text v-if="!showCountdown" class="text-button" @tap="getCode">获取验证码</text>
			<button v-else class="text-button">
				<uni-countdown
					:show-day="false"
					:hour="false"
					:minute="false"
					:second="10"
					@timeup="showCountdown = false"
					color="#16c2a3"
				></uni-countdown>
			</button>
		</uni-forms-item>

		<view class="agreement">
			<radio :checked="isAgree" @tap="radioChange" color="#16C2A3" />
			我已同意
			<text class="link">用户协议</text>
			及
			<text class="link">隐私协议</text>
		</view>

		<button @tap="loginFunc" class="uni-button">登 录</button>
	</uni-forms>
</template>

<script>
	export default {
		options: {
			styleIsolation: 'shared',
		},
	}
</script>

<style lang="scss">
	@import './styles.scss';
</style>
